<template>
  <div class="page-content">
    <div class="header">
      <h3>推广设置</h3>
    </div>
    <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick" style="margin-top: 20px">
      <el-tab-pane label="规则设置" name="0"> </el-tab-pane>
      <el-tab-pane label="推广员端" name="1"> </el-tab-pane>
      <el-tab-pane label="分享海报设置" name="2"> </el-tab-pane>
    </el-tabs>
    <el-form label-width="120px" style="margin-top: 20px" v-if="activeName === '0'" :model="formData">
      <el-form-item label="分销模式：">
        <el-radio-group v-model="formData.brokerageMode" :disabled="!isEdit" @change="handleChangeBrokerageMode">
          <el-radio value="01" border>默认模式</el-radio>
          <el-radio value="02" border>链动裂变2+1</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="招募计划：">
        <el-radio-group v-model="formData.enabled" :disabled="!isEdit">
          <el-radio value="1">开启</el-radio>
          <el-radio value="0">关闭</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item v-if="formData.enabled === '1'">
        <el-radio-group v-model="formData.enabledCondition" :disabled="!isEdit">
          <el-radio value="2" border>用户申请</el-radio>
          <el-radio value="1" border>人人推广</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="分销员审核：" v-if="formData.enabledCondition === '2' && formData.enabled === '1'">
        <el-radio-group v-model="formData.brokerAuditEnabled" :disabled="!isEdit">
          <el-radio value="1">开启</el-radio>
          <el-radio value="0">关闭</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="加入条件：" v-if="formData.enabledCondition === '2' && formData.enabled === '1'">
        <el-radio-group v-model="radio_join" :disabled="!isEdit || formData.brokerageMode === '02'">
          <el-radio value="0">无条件</el-radio>
          <el-radio value="1">有条件</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item v-if="formData.enabledCondition === '2' && formData.enabled === '1' && radio_join === '1'">
        <el-radio-group v-model="radio_buy" :disabled="!isEdit || formData.brokerageMode === '02'">
          <el-radio value="1" border>购买全店任意商品</el-radio>
          <el-radio value="0" border>购买以下任一商品</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item v-if="
        formData.enabledCondition === '2' &&
        formData.enabled === '1' &&
        radio_join === '1' &&
        radio_buy === '0'
      ">
        <el-radio-group v-model="formData.joinConditionEnabled" :disabled="!isEdit || formData.brokerageMode === '02'">
          <el-radio value="2">购买班型</el-radio>
          <el-radio value="3">购买会员卡</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="直推平级奖：" v-if="formData.brokerageMode === '02'">
        <el-radio-group v-model="formData.enableSameLevel" :disabled="!isEdit">
          <el-radio value="1">开启</el-radio>
          <el-radio value="0">关闭</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="奖励佣金：" v-if="formData.brokerageMode === '02' && formData.enableSameLevel === '1'">
        <div class="brokerage-tips">举例：一级推广员A发展B成为默认等级的普通推广员，B升级成为一级推广员时，B脱离A的推广网络，同时B成为A的直推平级；
          此后B的下线不再为A产生间推佣金，但B所得的佣金，A均可按比例获得对应奖励，奖励由平台承担。</div>
        <div><span>直推下级推广员升级为二级后，他所得佣金的</span><el-input v-model.number="formData.sameLevelRatio" style="width: 200px" :disabled="!isEdit"><template #append>%</template></el-input><span>作为直推平级奖励</span></div>
      </el-form-item>

      <h3 style="margin-bottom: 20px; margin-top: 40px"> 结算规则 </h3>
      <el-form-item label="结算时间：">
        <div>
          <div>
            <el-radio v-model="radio_settle" value="1" :disabled="!isEdit">交易完成后结算</el-radio>
          </div>
          <div>
            <el-radio v-model="radio_settle" value="0" style="margin-right: 0px" :disabled="!isEdit">交易完成</el-radio>
            <span>
              <el-input v-model="formData.frozenDays" placeholder="" style="width: 200px; margin: 0 10px"
                :disabled="!isEdit || radio_settle === '1'">
                <template #append> 天后结算 </template>
              </el-input>
            </span>
          </div>
          <!-- <div>
            2023年4月17日(GMT+00:00)起提交申请的商户号，交易完成时间为订单结算后7天。
          </div> -->
        </div>
      </el-form-item>
      <el-form-item label="自购分佣：">
        <div>
          <div>
            <el-radio v-model="formData.selfPurchaseBrokerageEnabled" label="1"
              :disabled="!isEdit">推广员与自己绑定客户关系，自购可获得商品佣金</el-radio>
          </div>
          <div>
            <el-radio v-model="formData.selfPurchaseBrokerageEnabled" label="0"
              :disabled="!isEdit">推广员不与自己绑定客户关系，自购不可获得商品佣金</el-radio>
          </div>
        </div>
      </el-form-item>
      <h3 style="margin-bottom: 20px; margin-top: 20px">提现设置</h3>
      <el-form-item label="提现开关：">
        <el-radio-group v-model="formData.withdrawEnabled" :disabled="!isEdit">
          <el-radio :value="1">开启</el-radio>
          <el-radio :value="0">关闭</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="可提现渠道：">
        <el-checkbox-group v-model="formData.withdrawTypes" :disabled="!isEdit">
          <el-checkbox value="01">微信</el-checkbox>
          <el-checkbox value="02">支付宝</el-checkbox>
          <el-checkbox value="03">银行卡</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item label="最低提现金额：">
        <el-input-number v-model="formData.withdrawMinPrice" :disabled="!isEdit" style="margin-right: 5px;" /> 元
      </el-form-item>
      <el-form-item label="每单抽取费率：">
        <el-input-number v-model="formData.withdrawFeePercent" :disabled="!isEdit" style="margin-right: 5px;" />%
      </el-form-item>
      <el-form-item label="提现手续费：">
        <span style="margin-right: 10px;">最低</span>
        <el-input-number v-model="formData.withdrawMinFee" :min="0" :step="0.01" :precision="2"
          style="width: 160px; margin-right: 5px;" :disabled="!isEdit" />
        <span style="margin-right: 10px;">元 / 最高</span>
        <el-input-number v-model="formData.withdrawMaxFee" :min="0" :step="0.01" :precision="2"
          style="width: 160px; margin-right: 5px;" :disabled="!isEdit" />
        <span>元</span>
      </el-form-item>
      <el-form-item label="提现间隔周期：">
        <el-input-number v-model="formData.withdrawInterval" :disabled="!isEdit" style="margin-right: 5px;" /> 天
      </el-form-item>
      <el-form-item label="提现说明：">
        <ArtWangEditor v-model="formData.withdrawInstruction" class="addcont" style="width: 100%;" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" style="width: 90px" v-if="!isEdit" @click="edit">
          编辑
        </el-button>
        <el-button type="primary" style="width: 90px" v-if="isEdit" @click="handleSave" :loading="btnLoding">
          保存
        </el-button>
      </el-form-item>
    </el-form>
    <el-form label-width="100px" v-if="activeName === '1'" :model="formData">
      <h3 style="margin-bottom: 20px; margin-top: 20px">基础设置</h3>
      <el-form-item label="推广员名称：">
        <el-input placeholder="支持自定义店铺推广员名称" v-model="formData.wxPromoterName" :disabled="!isEdit"></el-input>
      </el-form-item>
      <el-form-item label="分享标题：">
        <el-input placeholder="请输入分享标题" v-model="formData.shareTitle" :disabled="!isEdit"></el-input>
      </el-form-item>
      <el-form-item label="分享图片：">
        <div class="avatar-uploader" @click="openImageDialog('shareBackground')">
          <el-image v-if="formData.shareBackground" :src="formData.shareBackground" class="avatar"
            fit="cover"></el-image>
          <i v-else class="el-icon-plus avatar-uploader-icon"><el-icon>
              <Plus />
            </el-icon></i>
          <div v-if="formData.shareBackground" class="mask">替换</div>
          <el-icon v-if="formData.shareBackground" class="del-image" :size="20"
            @click.stop="handleDelBackgroundImage('shareBackground')">
            <CircleCloseFilled />
          </el-icon>
        </div>
      </el-form-item>
      <!--      <el-form-item label="公告栏标题：">-->
      <!--        <el-input-->
      <!--          placeholder="请输入公告栏标题"-->
      <!--          v-model="formData.wxTitle"-->
      <!--          :disabled="!isEdit"-->
      <!--        ></el-input>-->
      <!--      </el-form-item>-->
      <el-form-item label="推广说明：">
        <!-- <Editor v-model="formData.wxText" /> -->
        <ArtWangEditor v-model="formData.wxText" class="addcont" style="width: 100%;" />
      </el-form-item>
      <h3 style="margin-bottom: 20px; margin-top: 20px">申请页面背景图</h3>
      <el-form-item label="背景图：">
        <div class="avatar-uploader" @click="openImageDialog('promoterPageBackground')">
          <el-image v-if="formData.promoterPageBackground" :src="formData.promoterPageBackground" class="avatar"
            fit="cover"></el-image>
          <i v-else class="el-icon-plus avatar-uploader-icon"><el-icon>
              <Plus />
            </el-icon></i>
          <div v-if="formData.promoterPageBackground" class="mask">替换</div>
          <el-icon v-if="formData.promoterPageBackground" class="del-image" :size="20"
            @click.stop="handleDelBackgroundImage('promoterPageBackground')">
            <CircleCloseFilled />
          </el-icon>
        </div>
      </el-form-item>

<!--      <h3 style="margin-bottom: 20px; margin-top: 20px">推广店铺海报</h3>-->
<!--      <el-form-item label="自定义海报：">-->
<!--        <div :class="posterUrls.length ? '' : 'avatar-uploader'" @click="openImageDialog(false, 'posters')"-->
<!--          style="min-height: 120px; display: flex; flex-wrap: wrap">-->
<!--          <template v-if="posterUrls.length">-->
<!--            <div v-for="(url, idx) in posterUrls" :key="url + idx" class="avatar-item">-->
<!--              <el-image :src="url" class="avatar" fit="cover" />-->
<!--              <div class="mask" @click.stop="openImageDialog(false, 'posters', idx)">替换</div>-->
<!--              <el-icon class="del-image" :size="20" @click.stop="handleDelPoster(idx)">-->
<!--                <CircleCloseFilled />-->
<!--              </el-icon>-->
<!--            </div>-->
<!--          </template>-->
<!--          <template v-else>-->
<!--            <i class="el-icon-plus avatar-uploader-icon">-->
<!--              <el-icon>-->
<!--                <Plus />-->
<!--              </el-icon>-->
<!--            </i>-->
<!--          </template>-->
<!--        </div>-->
<!--      </el-form-item>-->
      <el-form-item>
        <el-button type="primary" style="width: 90px" v-if="!isEdit" @click="edit">
          编辑
        </el-button>
        <el-button type="primary" style="width: 90px" v-if="isEdit" @click="handleSave" :loading="btnLoding">
          保存
        </el-button>
      </el-form-item>
    </el-form>

    <share-poster-setting v-if="activeName === '2'" :id="formData.id" :wx-img="formData.wxImg" :diy-data="formData.shareDiy"></share-poster-setting>

    <image-selected-dialog v-if="showImageChooseDialog" :single-type="selectImageSingle" :operation-type="false"
      :show-image-choose-dialog="showImageChooseDialog" @close-dialog="handleCloseImageDialog"></image-selected-dialog>
  </div>
</template>

<script setup lang="ts">
import type { TabsPaneContext } from 'element-plus'
import { getDefault, settingUpdate, settingAdd } from '@/api/marketing'
import ImageSelectedDialog from '@/views/decoration/diyComponents/ImageSelectedDialog.vue'
import { CircleCloseFilled, Plus } from '@element-plus/icons-vue'
import { useUserStore } from '@/store/modules/user'
import SharePosterSetting from './components/SharePosterSetting.vue'

const radio_join = ref('0')
const radio_buy = ref('1')
const radio_settle = ref('0')
const activeName = ref<string>('0')

// 海报图片数组（多张）
const posterUrls = ref<string[]>([])
// 图片选择弹窗：true 单选（用于单张背景/分享图），false 多选（用于海报）
const selectImageSingle = ref(true)
// 替换索引（-1 表示新增/整体替换）
const replaceImageIndex = ref(-1)

const formData = ref<Record<string, any>>({
  brokerageMode: '01',
  enableSameLevel: '1',
  sameLevelRatio: '',
  enabled: '1',
  enabledCondition: '2',
  brokerAuditEnabled: '0',
  joinConditionEnabled: '3',
  frozenDays: '1',
  selfPurchaseBrokerageEnabled: '0',
  id: '',
  wxPromoterName: '',
  wxTitle: '',
  wxText: '',
  shareTitle: '',
  shareBackground: '',
  promoterPageBackground: '',
  withdrawEnabled: '1',
  withdrawTypes: ['01'],
  withdrawMinPrice: 200,
  withdrawFeePercent: 0,
  withdrawMinFee: 1,
  withdrawMaxFee: 100,
  withdrawInterval: 7,
  withdrawInstruction: '',
  wxImg: '',
  shareDiy: ''
})

const isEdit = ref(false)
const showImageChooseDialog = ref(false)
const openFormKey = ref<string>('')

const edit = () => {
  isEdit.value = !isEdit.value
}

const handleClick = (tab: TabsPaneContext, event: Event) => {
  console.log(tab, event)
}
function openImageDialog(arg1: string | boolean, type: string = '', idx: number = -1): void {
  if (typeof arg1 === 'string') {
    // 单图选择：分享图/背景图
    selectImageSingle.value = true
    openFormKey.value = arg1
    replaceImageIndex.value = -1
  } else {
    // 多图：海报
    selectImageSingle.value = false
    openFormKey.value = type || 'posters'
    replaceImageIndex.value = idx
  }
  showImageChooseDialog.value = true
}

function handleDelBackgroundImage(key: string): void {
  formData.value[key] = ''
}

function handleCloseImageDialog(value: any): void {
  // 未选择内容直接关闭
  if (!value || (Array.isArray(value) && value.length === 0)) {
    showImageChooseDialog.value = false
    replaceImageIndex.value = -1
    return
  }
  if (selectImageSingle.value) {
    // 单图：直接赋值
    formData.value[openFormKey.value] = value.fileUrl
  } else {
    // 多图：海报
    if (replaceImageIndex.value >= 0 && value && value.length) {
      posterUrls.value.splice(replaceImageIndex.value, 1, value[0].fileUrl)
    } else if (value && value.length) {
      posterUrls.value = value.map((img: any) => img.fileUrl)
    }
  }
  showImageChooseDialog.value = false
  replaceImageIndex.value = -1
}

function handleDelPoster(index: number): void {
  posterUrls.value.splice(index, 1)
}

const getData = async () => {
  try {
    const res = await getDefault()
    if (res.code === '00000' && res.data) {
      formData.value.brokerageMode = res.data.brokerageMode
      formData.value.enableSameLevel = res.data.enableSameLevel
      formData.value.sameLevelRatio = res.data.sameLevelRatio / 100
      formData.value.enabled = String(res.data.enabled)
      formData.value.selfPurchaseBrokerageEnabled = String(res.data.selfPurchaseBrokerageEnabled)
      formData.value.enabledCondition = String(res.data.enabledCondition)
      formData.value.brokerAuditEnabled = String(res.data.brokerAuditEnabled)
      formData.value.joinConditionEnabled = String(res.data.joinConditionEnabled)
      formData.value.id = res.data.id
      formData.value.wxPromoterName = res.data.wxPromoterName || ''
      formData.value.wxTitle = res.data.wxTitle || ''
      formData.value.wxText = res.data.wxText || ''
      formData.value.shareTitle = res.data.shareTitle || ''
      formData.value.shareBackground = res.data.shareBackground || ''
      formData.value.promoterPageBackground = res.data.promoterPageBackground || ''
      formData.value.withdrawFeePercent = res.data.withdrawFeePercent / 100
      formData.value.withdrawTypes = res.data.withdrawTypes.split(',')
      formData.value.withdrawEnabled = res.data.withdrawEnabled
      formData.value.withdrawMinPrice = res.data.withdrawMinPrice / 100
      formData.value.withdrawMinFee = res.data.withdrawMinFee / 100
      formData.value.withdrawMaxFee = res.data.withdrawMaxFee / 100
      formData.value.withdrawInterval = res.data.withdrawInterval
      formData.value.withdrawInstruction = res.data.withdrawInstruction
      formData.value.shareDiy = res.data.shareDiy || ''
      formData.value.wxImg = res.data.wxImg || ''
      // 海报回填：逗号分隔字符串 -> 数组
      posterUrls.value = res.data.wxImg
        ? res.data.wxImg.split(',').map((url: string) => url.trim()).filter((u: string) => u)
        : []
      if (res.data.frozenDays === -1) {
        radio_settle.value = '1'
        formData.value.frozenDays = ''
      } else {
        radio_settle.value = '0'
        formData.value.frozenDays = res.data.frozenDays
      }
      // 加入条件和购买条件
      switch (formData.value.joinConditionEnabled) {
        case '0':
          radio_join.value = '0'
          break
        case '1':
          radio_join.value = '1'
          radio_buy.value = '1'
          break
        case '2':
          radio_join.value = '1'
          radio_buy.value = '0'
          break
        case '3':
          radio_join.value = '1'
          radio_buy.value = '0'
          break
      }
    } else {
      // 如果没有数据，提现开关默认开启
      formData.value.withdrawEnabled = 1
    }
  } catch {
  } finally {
  }
}

const btnLoding = ref(false)

const filterEmptyValues = (obj: any) => {
  const result: any = {}
  for (const key in obj) {
    if (obj[key] !== '' && obj[key] !== null && obj[key] !== undefined) {
      result[key] = obj[key]
    }
  }
  return result
}

function handleChangeBrokerageMode(mode: any) {
  if(mode === '02') {
    radio_join.value = '1'
    radio_buy.value = '0'
    formData.value.joinConditionEnabled = '2'
  }
}

const handleSave = async () => {
  isEdit.value = !isEdit.value
  try {
    btnLoding.value = true
    if (radio_join.value === '0') {
      formData.value.joinConditionEnabled = '0'
    } else if (radio_buy.value === '1') {
      formData.value.joinConditionEnabled = '1'
    }
    const wxImg = posterUrls.value.join(',')
    // console.log(wxImg, "wxImg====");

    const sameLevelRatio = Number(formData.value.sameLevelRatio) * 100
    const submitWithdrawFeePercent = Number(formData.value.withdrawFeePercent) * 100
    const submitWithdrawMinPrice = Number(formData.value.withdrawMinPrice) * 100
    const submitWithdrawMinFee = Number(formData.value.withdrawMinFee) * 100
    const submitWithdrawMaxFee = Number(formData.value.withdrawMaxFee) * 100
    const submitWithdrawTypes = formData.value.withdrawTypes.length
      ? formData.value.withdrawTypes.join(',')
      : formData.value.withdrawTypes

    let params = filterEmptyValues({
      ...formData.value,
      // wxImg,
      sameLevelRatio,
      withdrawFeePercent: submitWithdrawFeePercent,
      withdrawTypes: submitWithdrawTypes,
      withdrawMinPrice: submitWithdrawMinPrice,
      withdrawMaxFee: submitWithdrawMaxFee,
      withdrawMinFee: submitWithdrawMinFee
    })
    // radio_settle: 1=交易完成后结算, 0=交易完成N天后结算
    if (radio_settle.value === '1') {
      params.frozenDays = -1
    } else {
      params.frozenDays = formData.value.frozenDays
    }

    if (formData.value.id) {
      const res = await settingUpdate({
        ...params,
        wxImg,
        shareBackground: formData.value.shareBackground,
        promoterPageBackground: formData.value.promoterPageBackground
      })
      if (res.code === '00000') {
        ElMessage.success('编辑成功')
      }
    } else {
      const res = await settingAdd({
        ...params,
        isPrimary: 1
      })
      if (res.code === '00000') {
        ElMessage.success('新增成功')
      }
    }
    getData()
  } catch {
  } finally {
    btnLoding.value = false
  }
}
onMounted(() => {
  getData()
})
</script>

<style lang="scss" scoped>
.page-content {
  width: 100%;
  height: 100%;

  .header {
    padding-bottom: 15px;
    border-bottom: 1px solid var(--art-border-color);

    h3 {
      font-size: 18px;
      font-weight: bold;
    }
  }

  :deep(.el-form) {
    .el-form-item {
      max-width: 700px;
    }
  }
}

.check {
  color: #5f79d1;
}

:deep(.editor-wrapper) {
  z-index: 0;
}

.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  // overflow: hidden;
  min-width: 150px;
  min-height: 150px;
  line-height: 150px;
  text-align: center;

  .mask {
    position: absolute;
    bottom: 0;
    left: 0;
    width: 100%;
    height: 24px;
    background-color: rgba(0, 0, 0, 0.6);
    display: flex;
    align-items: center;
    justify-content: center;
    opacity: 0;
    transition: opacity 0.3s ease;
    color: #fff;
    font-size: 12px;
  }

  .del-image {
    display: none;
    position: absolute;
    top: 0;
    right: 0;
    cursor: pointer;
    color: #8c939d;
  }

  &:hover .mask {
    opacity: 1;
  }

  &:hover .del-image {
    display: block;
  }
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-item {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  width: 150px;
  height: 150px;
  margin-right: 8px;
  margin-bottom: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #fff;
  position: relative;
  overflow: hidden;

  // 默认隐藏mask
  .mask {
    position: absolute;
    bottom: 0;
    left: 0;
    width: 100%;
    height: 24px;
    background-color: rgba(0, 0, 0, 0.6);
    display: flex;
    align-items: center;
    justify-content: center;
    opacity: 0;
    transition: opacity 0.3s ease;
    color: #fff;
    font-size: 12px;
    cursor: pointer;
  }

  // 悬停时显示mask
  &:hover .mask {
    opacity: 1;
  }

  .del-image {
    display: none;
    position: absolute;
    top: 0;
    right: 0;
    cursor: pointer;
    color: #8c939d;
  }

  &:hover .del-image {
    display: block;
  }
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 150px;
  height: 150px;
  line-height: 150px;
  text-align: center;
}

.avatar {
  width: 150px;
  height: 150px;
  display: block;
}

.addcont {
  z-index: 1;
}

.brokerage-tips {
  font-size: 12px;
  color: #8c939d;
}
</style>
